package com.lpc.framework.base.Controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tk.mybatis.mapper.entity.Example;

import com.lpc.framework.Constants;
import com.lpc.framework.base.vo.AjaxCallBack;
import com.lpc.framework.base.vo.DataGrid;
import com.lpc.framework.search.Searchable;
import com.lpc.framework.service.CommonService;
import com.lpc.framework.util.PermissionList;
import com.lpc.framework.web.annoation.PageableDefaults;
import com.lpc.framework.web.annoation.QueryString;

/**
 * 基础CRUD 控制器
 * 
 * @author jiangjinlong
 *
 * @param <T>
 */
public abstract class AjaxCRUDController<T> extends BaseController<T> {

    protected PermissionList permissionList = null;

    protected abstract CommonService<T> getCommonService();

    /**
     * 权限前缀：如sys:user 则生成的新增权限为 sys:user:create
     */
    public void setResourceIdentity(String resourceIdentity) {
        if (!StringUtils.isEmpty(resourceIdentity)) {
            permissionList = PermissionList.newPermissionList(resourceIdentity);
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    @PageableDefaults(sort = "id=desc")
    public String index(Model model) {
        return list(model);
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    @PageableDefaults(sort = "id=desc")
    public String list(Model model) {
        if (permissionList != null) {
            this.permissionList.assertHasViewPermission();
        }
        return viewName("list");
    }

    @RequestMapping(value = "datagrid")
    @PageableDefaults(sort = "id=desc")
    @ResponseBody
    public DataGrid<T> datagrid(Searchable searchable, Model model) {
        if (permissionList != null) {
            this.permissionList.assertHasViewPermission();
        }
        Page<T> page = getCommonService().getPageExample(searchable);
        DataGrid<T> grid = new DataGrid<T>();
        grid.setList(page.getContent());
        grid.setPageCurrent(page.getNumber());
        grid.setPageSize(page.getSize());
        grid.setTotal(page.getTotalElements());
        return grid;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") Long id) throws InstantiationException, IllegalAccessException,
            NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {

        if (permissionList != null) {
            this.permissionList.assertHasViewPermission();
        }
        T t = getCommonService().findByIdAndYn(id);
        setCommonData(model);
        model.addAttribute("m", t);
        model.addAttribute(Constants.OP_NAME, "查看");
        return viewName("editForm");
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {

        if (permissionList != null) {
            this.permissionList.assertHasCreatePermission();
        }

        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "新增");
        if (!model.containsAttribute("m")) {
            model.addAttribute("m", newModel());
        }
        return viewName("editForm");
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String showUpdateForm(@QueryString T m, Model model) {

        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "修改");
        model.addAttribute("m", m);
        return viewName("editForm");
    }

    @RequestMapping(value = "view", method = RequestMethod.GET)
    public String showViewForm(@QueryString T m, Model model) {

        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "查看");
        model.addAttribute("m", m);
        return viewName("view");
    }

    @RequestMapping(value = "update", method = RequestMethod.POST, params = "add")
    @ResponseBody
    public AjaxCallBack create(Model model, @QueryString T m) {

        if (permissionList != null) {
            this.permissionList.assertHasCreatePermission();
        }
        int result = getCommonService().insert(m);
        if (result > 0) {
            return AjaxCallBack.newInstance().success().message("新增成功!");
        }
        return AjaxCallBack.newInstance().success().message("新增失败!");
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxCallBack update(Model model, @QueryString T m) {

        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }
        int result = getCommonService().modifyById(m);
        if (result > 0) {
            return AjaxCallBack.newInstance().success().message("修改成功!");
        }
        return AjaxCallBack.newInstance().fail().message("修改失败!");
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxCallBack deleteById(String id) {

        if (permissionList != null) {
            this.permissionList.assertHasDeletePermission();
        }
        Object[] idArray = id.split(",");
        Example example = new Example(entityClass);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        int result = getCommonService().logicalDeletion(example);
        if (result == idArray.length) {
            return AjaxCallBack.newInstance().success().message("删除成功!");
        }
        return AjaxCallBack.newInstance().fail().message("删除失败!");
    }

}
